//
//  SEGActivitySignViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/19.
//  Copyright © 2017年 陈区. All rights reserved.
//

// ViewController
#import "SEGActivitySignViewController.h"
#import "SEGActicityTaskDetailViewController.h"
#import "SEGStaffDetailPresentationController.h"

// View
#import "SEGSignADCell.h"
#import "SEGActivitySignAlertView.h"
#import "SEGActivityLotteryBubbleButton.h"
#import "SEGIntegralExchangeTableViewCell.h"
#import "SEGActivityTaskMainCell.h"

#if __has_include(<SEGPlatform/CommonViewsHeader.h>)
#import <SEGPlatform/CommonViewsHeader.h>
#else
#import "CommonViewsHeader.h"
#endif

#if __has_include(<SEGStandard/SEGAdvertisementView.h>)
#import <SEGStandard/SEGAdvertisementView.h>
#else
#import "SEGAdvertisementView.h"
#endif

// Model
#import <SEGPlatform/SEGIntegralExchangeModel.h>

#if __has_include(<Common/SEGAdvertisementManager.h>)
#import <Common/SEGAdvlistManager.h>
#else
#import "SEGAdvlistManager.h"
#endif

// ViewModel
#import <SEGViewModel/SEGSignActivityDetailViewModel.h>

#import "SEGTarget_ActivityManage.h"
#import <SEGPlatform/SEGAdDisplayManager.h>

// 广告
#import "GDTUnifiedNativeAd.h"
#import "GDTUnifiedNativeAdView.h"
#import "SEGTencentTableViewCell.h"
#import "SEGCardDataModel.h"

#define kRulesLabel_defaultH 48.f
@interface SEGActivitySignViewController ()<UITableViewDelegate, UITableViewDataSource,GDTUnifiedNativeAdDelegate, GDTUnifiedNativeAdViewDelegate>

/** 活动签到弹窗 */
@property (nonatomic, strong) SEGActivitySignAlertView *signAlertView;
/** header */
@property (nonatomic, strong) UIView *headView;
/** 表格 */
@property (nonatomic, strong) UITableView *tableView;
/** 头部抽奖视图 */
@property (nonatomic, strong) UIImageView *headBgImgView;
/** 签到天数 */
@property (nonatomic, strong) UILabel *signDaysLabel;
/** 积分数 */
@property (nonatomic, strong) UILabel *integralLab;
/** 签到明细白色背景 */
@property (nonatomic, strong) UIView *signBackView;
/** 签到明细容器 */
@property (nonatomic, strong) UIView *signDetailContainer;
/** 是否已经请求了签到列表接口 */
@property (nonatomic, assign) BOOL isAlreayRequestSignDetail;
/** 规则说明内容 */
@property (nonatomic, strong) UILabel *rulesLabel;
/** 更多按钮 */
@property (nonatomic, strong) UIButton *moreBtn;
/** 签到规则视图 */
@property (nonatomic, strong) UIView *signRuleView;
/** 签到规则文案 */
@property (nonatomic, strong) UITextView *signRuleTextView;
/** 积分商城兑换数据 */
@property (nonatomic, strong) NSArray<SEGIntegralExchangeModel *> *integralExchangeModels;
/** 广告数据 */
@property (nonatomic, strong) NSArray<SEGAdvertismentModel*> *adSourceArr;
/** ViewModel */
@property (nonatomic, strong) SEGSignActivityDetailViewModel *acticityDetailViewModel;
/** 积分Cell */
@property (nonatomic, weak) SEGIntegralExchangeTableViewCell *exchangeCell;
/** 任务列表数据 */
@property (nonatomic, strong) NSArray<SEGActivityTaskModel *> *taskModelArray;
/** 是否需要刷新数据（去完成任务回来的时候需要）*/
@property (nonatomic, assign) __block BOOL needRefreshData;

/// 腾讯广告
@property (nonatomic, strong) NSArray<GDTUnifiedNativeAdDataObject *> *adDataArray;
@property (nonatomic, strong) GDTUnifiedNativeAd *unifiedNativeAd;
@property (nonatomic, strong) NSMutableArray<SEGCardDataModel *> *tencentSource;

@end

@implementation SEGActivitySignViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"🍬 %s", __func__);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self seg_checkActivityLotteryBubble];
    
    // 刷新数据
    if (self.needRefreshData) {
        self.needRefreshData = NO;
        [self refreshData];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.exchangeCell endTimer];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"福利社";
    self.view.backgroundColor = kColor_bg;
    
    _tencentSource = [NSMutableArray array];
    
    [self showCustomNavigationBackButton];
    // UI
    [self seg_setUpSubviews];
    // 初始化ViewModel数据
    self.acticityDetailViewModel.actId = self.actId;
    [self refreshData];
    
    WeakSelf;
    //收到活动抽奖推送
    [[NSNotificationCenter defaultCenter] addObserverForName:SEGActivityLotteryNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf seg_checkActivityLotteryBubble];
    }];
    
    //收到任务完成的推送后刷新数据
    [[NSNotificationCenter defaultCenter] addObserverForName:SEGRefreshActivitySignVCNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.needRefreshData = YES;
//        [weakSelf refreshData];
    }];
}

/// 判断是否显示活动抽奖气泡
- (void)seg_checkActivityLotteryBubble {
    [[SEGUhomeMediator sharedInstance] seg_checkActivityLotteryBubble:@{@"vc" : self}];
}

#pragma mark - Load Data
- (void)refreshData {
    // 查询活动详情 -> 查询签到详情 -> (未签到)签到
    [self loadActicityDetailData];
    // 获取总积分
    [self loadTotalIntegralData];
}

- (void)loadActicityDetailData {
    [SVProgressHUD show];
    /*
     5.0.0 需求 数据按顺序加载
     活动详情 -> 签到详情 -> 签到
            -> 任务 -> 积分抢兑 -> 广告
     */
    @weakify(self);
    [self.acticityDetailViewModel.activityDetailSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        // 活动详情请求成功 再展示tableheader
        [self setupHeaderView];
        [self loadSignDetailData];
        [self loadTaskList];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        // 重载数据的时候 如果请求失败则置空header
        self.tableView.tableHeaderView = nil;
        [self.tableView reloadData];
        [self loadTaskList];
    }];
}

// 请求签到详情
- (void)loadSignDetailData {
    @weakify(self);
    // 查询签到详情
    [self.acticityDetailViewModel.signDetailSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        if ([x boolValue]) {
            [self loadSubmitSign];
            // 如果是第一次请求签到详情接口 用户未签到 则展开
            [self openSignDetailView];
            [self.tableView reloadData];
        }
        // 设置背景图
        NSURL *imgUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,self.acticityDetailViewModel.signModel.signPic]];
        [self.headBgImgView setImageWithURL:imgUrl
                               placeholderImage:SEGAutoPicName(@"btn_bg_check")];
        // 刷新headView
        [self seg_updateSubviewsWithSignModel:self.acticityDetailViewModel.signModel];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        // 重载数据失败的时候 需要清楚数据
        [self.signDetailContainer removeAllSubviews];
    }];
}

// 请求进行签到
- (void)loadSubmitSign {
    @weakify(self);
    [self.acticityDetailViewModel.submitSignSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        RACTupleUnpack(NSString *errorMessage, NSNumber *value, NSNumber *type) = x;
        [SEGAlertView showTmepMessageWithMessage:errorMessage];
        // 签到成功弹窗
        SignAwardType signType = type.integerValue == 0 ? SIGNTYPE_integral : SIGNTYPE_growthValue;
        [self.signAlertView signAlertView_refreshAlertViewWithType:signType value:value.integerValue];
        [self.signAlertView show];
        // 查询签到详情
        [self loadSignDetailData];
        // 获取总积分
        [self loadTotalIntegralData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        NSString *noAuthTitle = error.userInfo[SEGActicityErrorNoAuthTitleKey];
        if (noAuthTitle.length > 0) {
            SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
                           [alertView showWithAlertText:noAuthTitle delegate:self buttonTitlesArray:@[@"取消", @"申请认证"]];
            return;
        }
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

// 请求任务列表
- (void)loadTaskList {
    @weakify(self);
    [self.acticityDetailViewModel.fetchTaskListSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        self.taskModelArray = [x copy];
        [self.tableView reloadData];
        [self loadIntegralExchangeData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        // 重新请求的时候 需要置空数据
        self.taskModelArray = nil;
        [self.tableView reloadData];
        [self loadIntegralExchangeData];
    }];
}

// 请求积分抢兑
- (void)loadIntegralExchangeData {
    // 4.9.6 需求 签到>积分抢兑>广告 数据按顺序加载
    @weakify(self);
    [self.acticityDetailViewModel.integralEexchangeSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        self.integralExchangeModels = x;
        [self.tableView reloadData];
        [self loadAdData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        // 重新请求的时候 需要置空数据
        self.integralExchangeModels = nil;
        [self.tableView reloadData];
        [self loadAdData];
    }];
}

// 加载广告数据
- (void)loadAdData {
    [self loadAds];
}

// 请求总积分数据
- (void)loadTotalIntegralData {
    @weakify(self);
    [self.acticityDetailViewModel.totalIntegralSignal subscribeNext:^(id  _Nullable x) {
        // 处理总积分逻辑
        @strongify(self);
        self.integralLab.text = ValueToString(x);
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}
 
#pragma mark - UI
- (void)seg_setUpSubviews {
    [self.view addSubview:self.tableView];
}

- (void)setupHeaderView {
    if (self.tableView.tableHeaderView) {
        return;
    }
    
    // 背景图
    [self.headView addSubview:self.headBgImgView];
    self.headBgImgView.image = SEGAutoPicName(@"btn_bg_check");
    [self.headBgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(LYScreenWidth()*220/750.0);
    }];
    // 积分
    [self.headView addSubview:self.integralLab];
    [self.integralLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_equalTo(20);
    }];
    WeakSelf;
    UIButton *checkIntegrateButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"总积分" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_pocketmoney_arrow_w")] forState:UIControlStateNormal];
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -6, 0, 0)];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 52, 0, 0)];
        button.titleLabel.font = kFont_13;
        [self.headView addSubview:button];
        button;
    });
    [[checkIntegrateButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSDictionary *params = @{@"linkURL":kIntegarlShop};
        UIViewController *VC = [[SEGUhomeMediator sharedInstance]seg_initWebViewLoadController:params];
        [weakSelf.navigationController pushViewController:VC animated:YES];
    }];
    [checkIntegrateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(self.integralLab.mas_bottom).mas_offset(-8);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
    }];
    
    UIView *signBackView = [[UIView alloc] init];
    signBackView.backgroundColor = kColor_W;
    signBackView.layer.shadowColor = [kColor_3 colorWithAlphaComponent:0.22].CGColor;
    signBackView.layer.shadowOffset = CGSizeMake(0,0);
    signBackView.layer.shadowOpacity = 1;
    signBackView.layer.shadowRadius = 8;
    signBackView.layer.cornerRadius = 8;
    self.signBackView = signBackView;
    // 连续签到背景图 默认折叠
    [self.headView addSubview:signBackView];
    [signBackView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_offset(-15);
        make.bottom.mas_equalTo(-10);
        make.height.mas_equalTo(56);
    }];

    // 签到天数
    self.signDaysLabel = [[UILabel alloc] init];
    self.signDaysLabel.font = [UIFont boldSystemFontOfSize:15];
    self.signDaysLabel.textColor = kColor_1;
    self.signDaysLabel.attributedText = [SEGUtils getAttributedWithString:@"已连续签到0天"
                                                                    Color:kColor_T
                                                                     font:[UIFont boldSystemFontOfSize:15.f]
                                                                    range:NSMakeRange(5, 2)];

    [signBackView addSubview:self.signDaysLabel];
    [self.signDaysLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(20);
        make.height.mas_equalTo(15);
    }];

    // ----- 签到规则 -----
    UIButton *ruleButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"签到规则" forState:UIControlStateNormal];
        [button setTitleColor:kColor_3 forState:UIControlStateNormal];
        [button setImage:SEGAutoPicName(@"icon_guize") forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button setContentEdgeInsets:UIEdgeInsetsMake(0, 4, 0, 0)];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, -4, 0, 0)];
        [signBackView addSubview:button];
        button;
    });
    [[ruleButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.signRuleView.alpha = 0;
        [[UIApplication sharedApplication].keyWindow addSubview:weakSelf.signRuleView];
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.signRuleView.alpha = 1;
        }];
    }];
    [ruleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.equalTo(self.signDaysLabel);
        make.height.mas_equalTo(30);
    }];

    [signBackView addSubview:self.signDetailContainer];
    self.signDetailContainer.hidden = YES; // 默认关闭
    [self.signDetailContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.signDaysLabel.mas_bottom).offset(15);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(80);
    }];

    // 更多按钮
    [signBackView addSubview:self.moreBtn];
    self.moreBtn.selected = YES; // 默认折叠
    [self.moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_offset(0);
        make.height.mas_equalTo(30);
    }];

    // 签到规则
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[self.acticityDetailViewModel.detailModel.rulesDesc dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    self.signRuleTextView.attributedText = attributedString;

    // 添加headerView
    self.tableView.tableHeaderView = self.headView;
}

- (void)seg_updateSubviewsWithSignModel:(SEGActivitySignModel *)signModel {
    // 签到天
    if ([signModel.continuousDays isEqualToString:@""] || !signModel.continuousDays) signModel.continuousDays = @"0";
    NSString *signDayStr = [NSString stringWithFormat:@"已连续签到%@天",signModel.continuousDays];
    self.signDaysLabel.attributedText = [SEGUtils getAttributedWithString:signDayStr
                                                                    Color:kColor_T
                                                                     font:[UIFont boldSystemFontOfSize:15.f]
                                                                    range:NSMakeRange(5, signModel.continuousDays.length+1)];
    
    // 签到卡片
    NSUInteger totalDays = signModel.signAwards.count;//根据返回天数
    CGFloat left_padding = 6;
    CGFloat card_W = (LYScreenWidth()-60-36)/7.0;
    CGFloat card_H = 47.f;
    
    //先移除 再刷新
    [self.signDetailContainer removeAllSubviews];
    
    for (int i = 1; i <= totalDays; i ++) {
        // cardView
        UIView *cardView = [[UIView alloc] init];
        cardView.frame = CGRectMake((card_W+left_padding)*(i-1), 0, card_W, card_H);
        cardView.layer.cornerRadius = 5.f;
        cardView.layer.masksToBounds = YES;
        [self.signDetailContainer addSubview:cardView];
        
        SEGActivitySignAwardModel *awardModel = signModel.signAwards[i-1];
        // value
        UILabel *valueLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 8, cardView.width, 10)];
        valueLab.textColor = kColor_1;
        valueLab.textAlignment = NSTextAlignmentCenter;
        valueLab.text = [NSString stringWithFormat:@"+%@",awardModel.awardValue];
        [cardView addSubview:valueLab];
        // icon
        UIImageView *iconView = [[UIImageView alloc] init];
        [cardView addSubview:iconView];
        if (i <= [signModel.continuousDays intValue]) { // 已签到
            cardView.backgroundColor = kColor_T;
            valueLab.font = [UIFont boldSystemFontOfSize:11];
            iconView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_success")];
            iconView.frame = CGRectMake((cardView.width-19)/2,
                                        valueLab.bottom+9,
                                        19,
                                        13);
        } else {
            cardView.backgroundColor = [UIColor colorWithHexString:@"#F0F0F0"];
            valueLab.font = [UIFont systemFontOfSize:11];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientSmallImageRootURL,awardModel.pic]];
            UIImage *placeholderImage = nil;
            if ([awardModel.awardType isEqualToString:@"1"]) {//奖励类型(1:积分,2:成长值)
                placeholderImage = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_gold")];
            } else {
                placeholderImage = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_growup")];
            }
            iconView.image = placeholderImage;
            if (awardModel.pic && awardModel.pic.length != 0) [iconView setImageWithURL:url placeholderImage:placeholderImage];
            iconView.frame = CGRectMake((cardView.width-16)/2,
                                        valueLab.bottom+6,
                                        16,
                                        17);
        }
        iconView.contentMode = UIViewContentModeScaleToFill;
        
        // day
        UILabel *dayLabel = [[UILabel alloc] init];
        dayLabel.font = kFont_11;
        dayLabel.textAlignment = NSTextAlignmentCenter;
        dayLabel.textColor = kColor_3;
        [self.signDetailContainer addSubview:dayLabel];
        dayLabel.frame = CGRectMake(cardView.x, cardView.bottom, cardView.width, 20);
        dayLabel.text = [NSString stringWithFormat:@"%@天",awardModel.signDays];
    }
    self.tableView.tableHeaderView = self.headView;
}

// 数据加载完成后刷新视图
- (void)updateUIAfterLoadDataFinish {
    
    [SVProgressHUD dismiss];
    // 如果活动详情失败 & 任务列表为空 & 没有积分抢兑数据 & 没有广告 则显示缺省
    if (!(self.acticityDetailViewModel.detailModel.actObj || self.taskModelArray.count > 0 || self.integralExchangeModels.count > 0 || self.adSourceArr.count > 0)) {
        NSDictionary *hudParams = @{@"view"     : self.view,
                                    @"text"     : kNoDataDefaultMessage,
        };
        [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:hudParams];
        self.tableView.hidden = YES;
    }
}

// 显示任务详情视图
- (void)showTaskDetailView:(SEGActivityTaskModel *)taskModel {
    WeakSelf;
    SEGActicityTaskDetailViewController *taskDetailViewController = [[SEGActicityTaskDetailViewController alloc] init];
    taskDetailViewController.taskModel = taskModel;
    taskDetailViewController.didSelectChildTask = ^(SEGActivityChildTaskModel * _Nonnull childTaskModel) {
        BOOL isJumpSuccess = [SEGTarget_ActivityManage getActivityTaskSkipViewController:childTaskModel presentVC:weakSelf nav:weakSelf.navigationController];
        if (isJumpSuccess) {
            weakSelf.needRefreshData = YES;
        }
    };
    SEGStaffDetailPresentationController *presentVC = [[SEGStaffDetailPresentationController alloc] initWithPresentedViewController:taskDetailViewController presentingViewController:self];
    taskDetailViewController.transitioningDelegate = presentVC;
    [self presentViewController:taskDetailViewController animated:YES completion:nil];
}

#pragma mark - Event
- (void)segNewAlertView:(UIView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self goToAuthViewController];
    }
}

- (void)goToAuthViewController {
    UIViewController *VC = [[SEGUhomeMediator sharedInstance] seg_initSubmitUserAtuhViewController:nil];
    VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)moreButtonClick:(UIButton *)button {
    button.selected = !button.selected;
    // 选中折叠，反之非选中展开
    if (button.selected) {
        [self foldSignDetailView];
    } else {
        [self openSignDetailView];
    }
}

// 展开签到
- (void)openSignDetailView {
    [self.signBackView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(137);
    }];
    self.moreBtn.selected = NO;
    self.signDetailContainer.hidden = NO;
    self.headView.frame = CGRectMake(0, 0, kScreenWidth, 236);
    // 添加headView
    self.tableView.tableHeaderView = self.headView;
}

// 折叠签到
- (void)foldSignDetailView {
    [self.signBackView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_offset(-15);
        make.bottom.mas_equalTo(-10);
        make.height.mas_equalTo(56);
    }];
    self.moreBtn.selected = YES;
    self.signDetailContainer.hidden = YES;
    self.headView.frame = CGRectMake(0, 0, kScreenWidth, 157);
    // 添加headView
    self.tableView.tableHeaderView = self.headView;
}

#pragma mark - 广告

/// 加载广告(系统广告、腾讯广告)
-(void)loadAds {
    // 加载系统广告逻辑
    [self loadSEGIAd];
}

/// 加载腾讯广告
- (void)loadTencentAd {
     self.unifiedNativeAd = [[GDTUnifiedNativeAd alloc] initWithPlacementId:kGDTPosIdActivitySign];
     self.unifiedNativeAd.delegate = self;
     [self.unifiedNativeAd loadAd];
}

/// 加载系统广告
-(void)loadSEGIAd {
    
    // 广告是最后一个接口 需要刷新UI
    [self.acticityDetailViewModel.adListSignal subscribeNext:^(id  _Nullable x) {
        self.adSourceArr = (NSArray *)x;
        
        [self.tableView reloadData];
        [self updateUIAfterLoadDataFinish];
    } error:^(NSError * _Nullable error) {
        // 重新请求的时候 需要重置数据
        self.adSourceArr = nil;
        [self.tableView reloadData];
        [self updateUIAfterLoadDataFinish];
    }];
}

- (void)segInsertData {
    // 插入腾讯广告占位数据
//    NSMutableArray<MessageModel *> *temp = [NSMutableArray arrayWithArray:self.viewModel.dataArray];
//    MessageModel *tencentAdItem = [[MessageModel alloc] init];
//    tencentAdItem.createTime = self.viewModel.dataArray.firstObject.createTime;
//    [temp insertObject:tencentAdItem atIndex:1];
//    self.viewModel.dataArray = [NSArray arrayWithArray:temp];
}

#pragma mark - GDTUnifiedNativeAdDelegate
- (void)gdt_unifiedNativeAdLoaded:(NSArray<GDTUnifiedNativeAdDataObject *> * _Nullable)unifiedNativeAdDataObjects error:(NSError * _Nullable)error {
    NSLog(@"广告数据回调,%s",__FUNCTION__);
    if (!error && unifiedNativeAdDataObjects.count > 0) {
        self.adDataArray = unifiedNativeAdDataObjects;
    }
    // 加载系统广告
    [self loadSEGIAd];
    NSLog(@"广告数据回调,%s,%@",__FUNCTION__,error.localizedDescription);
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 任务中心
    if (section == 0) {
        return self.taskModelArray.count > 0 ? 1 : 0;
    }
    // 积分抢兑
    if (section == 1) {
        return self.integralExchangeModels.count > 0 ? 1 : 0;
    }
    
    // 广告
    return self.adSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 任务中心
    if (indexPath.section == 0) {
        static NSString *taskCellId = @"activityTaskCellId";
        SEGActivityTaskMainCell *taskCell = [tableView dequeueReusableCellWithIdentifier:taskCellId];
        if (!taskCell) {
            taskCell = [[SEGActivityTaskMainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:taskCellId];
        }
        WeakSelf;
        taskCell.clickBlock = ^(NSInteger index) {
            SEGActivityTaskModel *taskModel = weakSelf.taskModelArray[index];
            if (taskModel.whetherReceive == 1) {
                // 已领取的任务之间展示任务详情
                [weakSelf showTaskDetailView:taskModel];
            } else {
                // 未领取任务需要先领取
                [SVProgressHUD show];
                [[weakSelf.acticityDetailViewModel.receiveTaskCommand execute:taskModel.exampleId] subscribeNext:^(id  _Nullable x) {
                    [SVProgressHUD dismiss];
                    taskModel.whetherReceive = 1;
                    [weakSelf.tableView reloadData];
                    [weakSelf showTaskDetailView:taskModel];
                } error:^(NSError * _Nullable error) {
                    [SVProgressHUD dismiss];
                    [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
                }];
            }
        };
        [taskCell updateViewWithTaskModelArray:self.taskModelArray];
        return taskCell;
    }
    // 积分抢兑
    if (indexPath.section == 1) {
        static NSString *exchangeCellId = @"exchangeCellId";
        SEGIntegralExchangeTableViewCell *exchangeCell = [tableView dequeueReusableCellWithIdentifier:exchangeCellId];
        if (!exchangeCell) {
            exchangeCell = [[SEGIntegralExchangeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:exchangeCellId];
        }
        [exchangeCell updateCellWithModelArray:self.integralExchangeModels];
        self.exchangeCell = exchangeCell;
        return exchangeCell;
    }
    
    // 广告
    static NSString *cellId = @"cellId";
    SEGSignADCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) cell = [[SEGSignADCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    SEGAdvertismentModel *model = self.adSourceArr[indexPath.row];
    [cell signADCell_refreshWithPicURL:model.pic];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        SEGAdvertismentModel *model = self.adSourceArr[indexPath.row];
        [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithType:[model yy_modelToJSONObject]];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 任务中心
    if (indexPath.section == 0) {
        return 174;
    }
    // 积分抢兑
    if (indexPath.section == 1) {
        return 98;
    }
    // 广告
    return 130;
}

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    [self.moreBtn setImage:SEGAutoPicName(@"btn_up")
              forState:UIControlStateNormal];
    [self.moreBtn setImage:SEGAutoPicName(@"btn_down")
              forState:UIControlStateSelected];
}

#pragma mark - Getter
- (SEGActivitySignAlertView *)signAlertView {
    if (!_signAlertView) {
        _signAlertView = [SEGActivitySignAlertView new];
        _signAlertView.hidden = YES;
        [[UIApplication sharedApplication].delegate.window addSubview:_signAlertView];
    }
    return _signAlertView;
}

- (UIView *)headView {
    if (!_headView) {
        CGRect rect = CGRectMake(0, 0, kScreenWidth, 157); // 默认折叠
        _headView = [[UIView alloc] initWithFrame:rect];
        _headView.backgroundColor = kColor_W;
    }
    return _headView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        CGRect rect = CGRectMake(0, 0, kScreenWidth, LYScreenHeight()-kNavigationBarAndStatusBarHeight);
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        _tableView.backgroundColor = kColor_bg;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 130.f;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

- (UIImageView *)headBgImgView {
    if (!_headBgImgView) {
        _headBgImgView = [[UIImageView alloc] init];
        _headBgImgView.contentMode = UIViewContentModeScaleToFill;
        _headBgImgView.userInteractionEnabled = YES;
    }
    return _headBgImgView;
}

- (UILabel *)integralLab {
    if (!_integralLab) {
        CGRect rect = CGRectMake(0, 44, self.headView.width, 29);
        _integralLab = [[UILabel alloc] initWithFrame:rect];
        _integralLab.font = [UIFont boldSystemFontOfSize:35];
        _integralLab.textColor = kColor_W;
        _integralLab.textAlignment = NSTextAlignmentCenter;
        _integralLab.text = @"0";
    }
    return _integralLab;
}

- (UIView *)signDetailContainer {
    if (!_signDetailContainer) {
        _signDetailContainer = [[UIView alloc] init];
        _signDetailContainer.clipsToBounds = YES;
    }
    return _signDetailContainer;
}

- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:SEGAutoPicName(@"btn_up")
                  forState:UIControlStateNormal];
        [_moreBtn setImage:SEGAutoPicName(@"btn_down")
                  forState:UIControlStateSelected];
        [_moreBtn addTarget:self
                     action:@selector(moreButtonClick:)
           forControlEvents:UIControlEventTouchUpInside];
        _moreBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _moreBtn.selected = YES;
    }
    return _moreBtn;
}

- (UIView *)signRuleView {
    if (!_signRuleView) {
        UIView *signRuleView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _signRuleView = signRuleView;
        _signRuleView.backgroundColor = kColor_bg3;
        
        UIButton *tapButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [_signRuleView addSubview:button];
            button;
        });
        [tapButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        [[tapButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [UIView animateWithDuration:0.3 animations:^{
                signRuleView.alpha = 0;
            } completion:^(BOOL finished) {
                [signRuleView removeFromSuperview];
            }];
        }];
        
        UIView *containerView = [[UIView alloc] init];
        containerView.backgroundColor = kColor_W2;
        containerView.layer.cornerRadius = 5;
        containerView.layer.masksToBounds = YES;
        [_signRuleView addSubview:containerView];
        [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_offset(0);
            make.width.mas_equalTo(270*LYScreenScaleWidth());
            make.height.mas_equalTo(183*LYScreenScaleHeight());
        }];
        
        UILabel *titleLabel = ({
            UILabel *label = [[UILabel alloc] init];
            label.numberOfLines = 0;
            label.text = @"签到规则";
            label.textColor = kColor_1;
            label.font = [UIFont boldSystemFontOfSize:16];
            [containerView addSubview:label];
            label;
        });
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(30);
            make.centerX.mas_offset(0);
        }];
        
        UIButton *confirmButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"我知道了" forState:UIControlStateNormal];
            [button setTitleColor:kColor_1 forState:UIControlStateNormal];
            button.titleLabel.font = kFont_16;
            [containerView addSubview:button];
            button;
        });
        [[confirmButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [UIView animateWithDuration:0.3 animations:^{
                signRuleView.alpha = 0;
            } completion:^(BOOL finished) {
                [signRuleView removeFromSuperview];
            }];
        }];
        [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_offset(0);
            make.height.mas_equalTo(44);
        }];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = kColor_L2;
        [containerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.equalTo(confirmButton.mas_top);
            make.height.mas_equalTo(0.5);
        }];
        
        [containerView addSubview:self.signRuleTextView];
        [self.signRuleTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(28);
            make.right.mas_equalTo(-28);
            make.top.equalTo(titleLabel.mas_bottom).offset(14);
            make.bottom.mas_equalTo(-58);
        }];
    }
    return _signRuleView;
}

- (UITextView *)signRuleTextView {
    if (!_signRuleTextView) {
        _signRuleTextView = [[UITextView alloc] init];
        _signRuleTextView.editable = NO;
        _signRuleTextView.backgroundColor = kColor_W2;
    }
    return _signRuleTextView;
}

- (SEGSignActivityDetailViewModel *)acticityDetailViewModel {
    if (!_acticityDetailViewModel) {
        _acticityDetailViewModel = [SEGSignActivityDetailViewModel new];
    }
    return _acticityDetailViewModel;
}

@end
